import express from "express";
import dotenv from "dotenv";
import path from "path";
import morgan from "morgan";
import connectDB from "./config/db.js";
import productRoutes from "./routes/productRoutes.js";
import userRoutes from "./routes/userRoutes.js";
import orderRoutes from "./routes/orderRoutes.js";
import uploadRoutes from "./routes/uploadRoutes.js";
import { notFound, errorHandler } from "./middleware/error.js";
import axios from "axios";

dotenv.config();
connectDB();

const app = express();

app.use(express.json());

//生产环境下
if (process.env.NODE_ENV == "development") {
  app.use(morgan("dev"));
}

//获取支付的status状态码
// app.get("/status", (req, res) => {
//   axios.get("https://www.thenewstep.cn/pay/logs/log.txt").then((response) => {
//     res.json({ status: response.data });
//   });
// });

// 获取paypal的clientID
app.get("/api/config/paypal", (req, res) => {
  res.send(process.env.PAYPAL_CLIENT_ID);
});

//商品路由
app.use("/api/products", productRoutes);
//用户路由
app.use("/api/users", userRoutes);
//订单路由
app.use("/api/orders", orderRoutes);
//文件上传路由
app.use("/api/upload", uploadRoutes);

//upload文件夹作为静态文件
const __dirname = path.resolve();
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));

//开发环境下
if (process.env.NODE_ENV == "production") {
  app.use(express.static(path.join(__dirname, "/frontend/build")));

  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "frontend", "build", "index.html"));
  });
}

//404错误处理中间件
app.use(notFound);
//错误处理中间件
app.use(errorHandler);

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`服务器在${process.env.NODE_ENV}模式下${PORT}端口号运行...`);
});
